// SPDX-License-Identifier: GPL-3.0-or-later

import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import Fk.Pages
import Fk.RoomElement
import QtMultimedia

GraphicsBox {
    id: root
    width: 800
    height: 600
    title.text: "御风飞行"

    // 游戏状态
    property bool gameRunning: false
    property int score: 0
    property int pipeScore: 0
    property real gravity: 1000
    property real jumpForce: -400
    property real birdSpeed: 200
    property bool operable : false
    
    property int pipeCount: 0 // 已生成的管道数量
    property int maxPipes: 3 // 最大管道数量
    property bool gameWin: false // 游戏是否胜利
    property real lastPipeX: 0 // 上一个管道的X位置
    property var stars: [] // 存储星星对象
    
    // 用于同步的对象ID
    property int nextObjectId: 1
    property var pipeIds: ({}) // 管道ID映射
    property var starIds: ({}) // 星星ID映射
    
    // 背景元素
    Rectangle {
        anchors.fill: parent
        color: "#87CEEB"
        
        Image {
            source: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='800' height='600' viewBox='0 0 800 600'%3E%3Cpath fill='%2333CCFF' d='M0 0h800v600H0z'/%3E%3Ccircle cx='100' cy='100' r='40' fill='white' opacity='0.7'/%3E%3Ccircle cx='200' cy='50' r='30' fill='white' opacity='0.7'/%3E%3Ccircle cx='300' cy='150' r='50' fill='white' opacity='0.7'/%3E%3Ccircle cx='500' cy='80' r='45' fill='white' opacity='0.7'/%3E%3Ccircle cx='700' cy='120' r='35' fill='white' opacity='0.7'/%3E%3C/svg%3E"
            anchors.fill: parent
        }

        // 地面
        Rectangle {
            id: ground
            width: parent.width
            height: 100
            anchors.bottom: parent.bottom
            color: "#8B4513"
            border.color: "#654321"
            border.width: 2
            
            Rectangle {
                width: parent.width
                height: 20
                anchors.top: parent.top
                color: "#7CFC00"
            }
        }

        // 小鸟
        Image {
            id: bird
            property int curr: 2
            source: "../image/anim/yufeng/nanhua" + curr + ".png"
            width: 60
            height: 68.75
            x: 150
            y: parent.height / 2 - height / 2
            z: 10
            
            property real velocity: 0

            onVelocityChanged: {
                if (velocity < -50) { // 跳跃时
                } else if (velocity > 50) { // 下落时
                    dropEffect.start();
                }
            }
        }

        // 管道管理器
        Item {
            id: pipeManager
            
            // 创建新管道 - 确保最小间距
            function createPipe() {
                if (root.pipeCount >= root.maxPipes) return;
                
                // 确保最小间距为一个管道宽度 (180像素)
                var minDistance = 180;
                var maxDistance = 540;
                
                // 计算管道位置
                var pipeX = root.width + minDistance + Math.random() * (maxDistance - minDistance);
                
                // 如果这不是第一个管道，确保与上一个管道有足够距离
                if (root.lastPipeX > 0) {
                    // 确保至少有一个管道宽度的间距 (180像素)
                    var minSpacing = 200;
                    while (pipeX - root.lastPipeX < minSpacing) {
                        pipeX += minSpacing;
                    }
                }
                else{
                    pipeX = root.width + 180;
                }
                
                // 创建上管道
                createTopPipe(pipeX);

                // 在管道间隙中生成星星
                var topStar = Math.random();
                if (root.pipeCount == 2 || topStar < 0.5) {
                    createStar(pipeX);
                }

                root.lastPipeX = pipeX;

                pipeX = root.width + minDistance + Math.random() * (maxDistance - minDistance);
                var minSpacing = 200;
                while (pipeX - root.lastPipeX < minSpacing) {
                    pipeX += minSpacing;
                }
                
                // 创建下管道 - 独立位置
                createBottomPipe(pipeX);
                
                root.lastPipeX = pipeX;
                root.pipeCount++;
                
                // 在管道间隙中生成星星
                if (root.pipeCount < 3 && topStar >= 0.5) {
                    createStar(pipeX);
                }
            }
            
            // 创建上管道
            function createTopPipe(pipeX) {
                // 随机管道高度和间距
                var pipeHeight = 100 + Math.random() * 200;
                var pipeSpacing = 180;
                
                // 分配唯一ID
                var objectId = root.nextObjectId++;
                
                // 创建上管道
                var topPipe = pipeComponent.createObject(pipeManager, {
                    "x": pipeX,
                    "y": 0,
                    "height": pipeHeight,
                    "isTop": true,
                    "objectId": objectId
                });
                
                pipes.push(topPipe)
                root.pipeIds[objectId] = topPipe;
                
                // 同步管道创建
                if (root.operable) {
                    var pipeData = {
                        type: "pipe",
                        id: objectId,
                        x: pipeX,
                        y: 0,
                        height: pipeHeight,
                        isTop: true
                    };
                    ClientInstance.notifyServer("PushRequest", "updatemini,sync," + JSON.stringify(pipeData));
                }
            }
            
            // 创建下管道
            function createBottomPipe(pipeX) {
                // 随机管道高度和间距
                var pipeHeight = 100 + Math.random() * 200;
                var pipeSpacing = 180;
                
                // 分配唯一ID
                var objectId = root.nextObjectId++;
                
                // 创建下管道
                var bottomPipe = pipeComponent.createObject(pipeManager, {
                    "x": pipeX,
                    "y": root.height - pipeHeight - ground.height,
                    "height": pipeHeight,
                    "isTop": false,
                    "objectId": objectId
                });
                
                pipes.push(bottomPipe)
                root.pipeIds[objectId] = bottomPipe;
                
                // 同步管道创建
                if (root.operable) {
                    var pipeData = {
                        type: "pipe",
                        id: objectId,
                        x: pipeX,
                        y: root.height - pipeHeight - ground.height,
                        height: pipeHeight,
                        isTop: false
                    };
                    ClientInstance.notifyServer("PushRequest", "updatemini,sync," + JSON.stringify(pipeData));
                }
            }
            
            // 在管道间隙中生成星星
            function createStar(pipeX) {
                // 星星出现在管道右侧25-125像素的位置
                var starX = pipeX + 80 + 25 + Math.random() * 100;
                
                // 星星在中间区域
                var starY = root.height * 0.3 + Math.random() * (root.height * 0.4);
                
                // 分配唯一ID
                var objectId = root.nextObjectId++;
                
                // 创建星星
                var star = starComponent.createObject(pipeManager, {
                    "x": starX,
                    "y": starY,
                    "objectId": objectId
                });
                
                root.stars.push(star);
                root.starIds[objectId] = star;
                
                // 同步星星创建
                if (root.operable) {
                    var starData = {
                        type: "star",
                        id: objectId,
                        x: starX,
                        y: starY
                    };
                    ClientInstance.notifyServer("PushRequest", "updatemini,sync," + JSON.stringify(starData));
                }
            }
            
            // 管道组件
            Component {
                id: pipeComponent
                Rectangle {
                    width: 80
                    color: "#228B22"
                    border.color: "#006400"
                    border.width: 3
                    
                    property bool isTop: false
                    property bool scored: false
                    property int objectId: 0
                    
                    // 管道顶部/底部装饰
                    Rectangle {
                        width: parent.width + 20
                        height: 30
                        anchors.horizontalCenter: parent.horizontalCenter
                        y: isTop ? parent.height - height : 0
                        color: "#228B22"
                        border.color: "#006400"
                        border.width: 3
                        radius: 10
                    }
                }
            }
            
            // 星星组件
            Component {
                id: starComponent
                Image {
                    source: "../image/anim/yufeng/xing.png"
                    width: 30
                    height: 30
                    z: 5
                    property int objectId: 0
                    
                    // 星星动画
                    RotationAnimation on rotation {
                        from: 0
                        to: 360
                        duration: 2000
                        loops: Animation.Infinite
                        running: true
                    }
                    
                    // 缩放动画
                    SequentialAnimation on scale {
                        loops: Animation.Infinite
                        running: true
                        NumberAnimation { from: 1.0; to: 1.2; duration: 500; easing.type: Easing.InOutQuad }
                        NumberAnimation { from: 1.2; to: 1.0; duration: 500; easing.type: Easing.InOutQuad }
                    }
                }
            }
            
            // 所有管道的数组
            property var pipes: []
        }
    }

    // 游戏计时器
    Timer {
        id: gameTimer
        interval: 16 // 约60FPS
        running: false
        repeat: true
        
        property real lastTime: 0
        property real deltaTime: 0
        
        onTriggered: {
            var currentTime = new Date().getTime();
            if (lastTime === 0) {
                deltaTime = 0.016; // 默认16ms
            } else {
                deltaTime = (currentTime - lastTime) / 1000; // 转换为秒
            }
            lastTime = currentTime;
            
            updateGame(deltaTime);
        }
    }
    
    // 游戏更新函数
    function updateGame(dt) {
        // 更新小鸟位置
        bird.velocity += gravity * dt;
        bird.y += bird.velocity * dt;
        
        // 移动管道
        for (var i = pipeManager.pipes.length - 1; i >= 0; i--) {
            var pipe = pipeManager.pipes[i]
            pipe.x -= birdSpeed * dt;
            
            // 检测小鸟通过管道（计分）
            if (!pipe.scored && pipe.x + pipe.width < bird.x - pipe.width && !pipe.isTop) {
                pipe.scored = true
                pipeScore++
                
                // 同步管道得分
                if (operable) {
                    var pipeData = {
                        type: "pipe-scored",
                        id: pipe.objectId
                    };
                    ClientInstance.notifyServer("PushRequest", "updatemini,sync," + JSON.stringify(pipeData));
                }
                
                // 检查是否通过所有管道
                if (pipeScore >= maxPipes) {
                    gameWin = true;
                    gameOver();
                }
            }
            
            // 移除屏幕外的管道
            if (pipe.x + pipe.width < 0) {
                // 移除本地管道
                delete pipeIds[pipe.objectId];
                pipe.destroy();
                pipeManager.pipes.splice(i, 1);
            }
            
            // 碰撞检测
            if (collision(bird, pipe)) {
                gameWin = false;
                gameOver();
            }
        }
        
        // 移动和检测星星
        for (var j = stars.length - 1; j >= 0; j--) {
            var star = stars[j];
            star.x -= birdSpeed * dt;
            
            // 检测小鸟与星星的碰撞
            if (starCollision(bird, star)) {
                // 收集星星
                score++;
                
                // 同步星星收集
                if (operable) {
                    var starData = {
                        type: "star-collected",
                        id: star.objectId
                    };
                    ClientInstance.notifyServer("PushRequest", "updatemini,sync," + JSON.stringify(starData));
                }
                
                // 移除本地星星
                star.destroy();
                delete starIds[star.objectId];
                stars.splice(j, 1);
                
                // 播放收集效果
                collectEffect.createObject(root, {
                    "x": star.x,
                    "y": star.y
                });
            }
            
            // 移除屏幕外的星星
            if (star.x + star.width < 0) {
                // 移除本地星星
                star.destroy();
                delete starIds[star.objectId];
                stars.splice(j, 1);
            }
        }
        
        // 创建新管道（最多4个）
        if (operable and frameCount % 100 === 0 && pipeCount < maxPipes) {
            pipeManager.createPipe();
        }
        
        // 检测与地面/天花板的碰撞
        if (operable && (bird.y + bird.height > root.height - ground.height || bird.y < 0)) {
            gameWin = false;
            gameOver();
        }
        
        frameCount++;
    }
    
    // 星星收集效果组件
    Component {
        id: collectEffect
        Item {
            id: effect
            width: 50
            height: 50
            
            property real animDuration: 500
            
            Image {
                source: "../image/anim/yufeng/xing.png"
                width: 40
                height: 40
                anchors.centerIn: parent
                
                RotationAnimation on rotation {
                    from: 0
                    to: 360
                    duration: effect.animDuration
                    running: true
                }
            }
            
            // 缩放和淡出动画
            ParallelAnimation {
                running: true
                NumberAnimation { target: effect; property: "scale"; from: 1.0; to: 2.0; duration: effect.animDuration }
                NumberAnimation { target: effect; property: "opacity"; from: 1.0; to: 0.0; duration: effect.animDuration }
                onFinished: effect.destroy()
            }
        }
    }
    
    property int frameCount: 0

    // 碰撞检测函数 - 使用圆形碰撞检测更精确
    function collision(obj1, obj2) {
        // 小鸟中心点
        var birdCenterX = obj1.x + obj1.width / 2;
        var birdCenterY = obj1.y + obj1.height / 2;
        var birdRadius = Math.min(obj1.width, obj1.height) * 0.4;
        
        // 管道边界
        var pipeLeft = obj2.x;
        var pipeRight = obj2.x + obj2.width;
        var pipeTop = obj2.y;
        var pipeBottom = obj2.y + obj2.height;
        
        // 检测小鸟中心点到管道边的最近点
        var closestX = Math.max(pipeLeft, Math.min(birdCenterX, pipeRight));
        var closestY = Math.max(pipeTop, Math.min(birdCenterY, pipeBottom));
        
        // 计算距离
        var distanceX = birdCenterX - closestX;
        var distanceY = birdCenterY - closestY;
        
        // 检测是否碰撞
        return (distanceX * distanceX + distanceY * distanceY) < (birdRadius * birdRadius);
    }
    
    // 星星碰撞检测函数
    function starCollision(obj1, obj2) {
        // 小鸟中心点
        var birdCenterX = obj1.x + obj1.width / 2;
        var birdCenterY = obj1.y + obj1.height / 2;
        var birdRadius = Math.min(obj1.width, obj1.height) * 0.4;
        
        // 星星中心点
        var starCenterX = obj2.x + obj2.width / 2;
        var starCenterY = obj2.y + obj2.height / 2;
        var starRadius = Math.min(obj2.width, obj2.height) * 0.5;
        
        // 计算中心点距离
        var distanceX = birdCenterX - starCenterX;
        var distanceY = birdCenterY - starCenterY;
        var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
        
        // 检测是否碰撞
        return distance < (birdRadius + starRadius);
    }

    // 游戏开始
    function startGame() {
        // 重置游戏状态
        gameRunning = true
        score = 0
        pipeScore = 0
        pipeCount = 0
        lastPipeX = 0
        nextObjectId = 1
        pipeIds = {}
        starIds = {}
        bird.y = root.height / 2 - bird.height / 2
        bird.velocity = 0
        bird.rotation = 0
        bird.curr = 1
        
        // 清除旧管道
        for (var i = 0; i < pipeManager.pipes.length; i++) {
            pipeManager.pipes[i].destroy()
        }
        pipeManager.pipes = []
        
        // 清除旧星星
        for (var j = 0; j < stars.length; j++) {
            stars[j].destroy()
        }
        stars = []
        
        // 创建第一个管道
        pipeManager.createPipe()
        
        // 启动游戏计时器
        frameCount = 0
        gameTimer.lastTime = 0;
        gameTimer.start()
        
        // 同步游戏开始
        if (operable) {
            var startData = {
                type: "game-start"
            };
            ClientInstance.notifyServer("PushRequest", "updatemini,sync," + JSON.stringify(startData));
        }
    }

    // 游戏结束
    function gameOver() {
        // 同步游戏结束
        if (operable) {
            gameRunning = false
            gameTimer.stop()

            var endData = {
                type: "game-end",
                win: gameWin,
                score: score
            };
            ClientInstance.notifyServer("PushRequest", "updatemini,sync," + JSON.stringify(endData));

            // 显示结果界面
            resultOverlay.visible = true;
        }
    }

    // 小鸟跳跃
    function jump() {
        if (!resultOverlay.visible && root.operable) {
            if (gameRunning) {
                bird.velocity = jumpForce;
                jumpEffect.start();
                
                // 同步跳跃事件
                if (operable) {
                    var jumpData = {
                        type: "jump"
                    };
                    ClientInstance.notifyServer("PushRequest", "updatemini,sync," + JSON.stringify(jumpData));
                }
            } else if (!gameRunning) {
                startGame()
            }
        }
    }
    
    // 跳跃效果
    SequentialAnimation {
        id: jumpEffect
        PropertyAnimation { target: bird; property: "curr"; to: 2; duration: 200 }
    }

    // 下落效果
    SequentialAnimation {
        id: dropEffect
        PropertyAnimation { target: bird; property: "curr"; to: 0; duration: 200 }
    }

    // 控制区域
    MouseArea {
        id: gameArea
        anchors.fill: parent
        onClicked: jump()
    }
    
    // 键盘控制
    Keys.onSpacePressed: jump()
    focus: true

    // 分数显示
    Text {
        anchors.top: parent.top
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.topMargin: 20
        text: "分数: " + score + " / " + maxPipes + (root.operable?"":"（旁观中）")
        font.pixelSize: 36
        font.bold: true
        color: "white"
        style: Text.Outline
        styleColor: "black"
    }

    // 开始界面
    Rectangle {
        id: startOverlay
        anchors.fill: parent
        color: "#80000000"
        visible: !gameRunning && !resultOverlay.visible
        
        Column {
            anchors.centerIn: parent
            spacing: 20
            
            Text {
                text: "御风飞行"
                font.pixelSize: 48
                font.bold: true
                color: "white"
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: "收集星星获取分数!"
                font.pixelSize: 32
                color: "gold"
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: "游戏说明：\n1. 点击屏幕或按空格键跳跃\n2. 避开管道和地面\n3. 收集星星获取分数\n4. 通过所有管道获胜"
                font.pixelSize: 20
                color: "#FFD700"
                anchors.horizontalCenter: parent.horizontalCenter
                horizontalAlignment: Text.AlignHCenter
            }
            
            Button {
                text: "开始游戏"
                anchors.horizontalCenter: parent.horizontalCenter
                onClicked: startGame()
                visible: root.operable
                
                background: Rectangle {
                    color: "#4CAF50"
                    radius: 10
                }
                
                contentItem: Text {
                    text: parent.text
                    font.pixelSize: 24
                    color: "white"
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                }
            }
        }
    }
    
    // 结果界面
    Rectangle {
        id: resultOverlay
        anchors.fill: parent
        color: "#80000000"
        visible: false
        
        Column {
            anchors.centerIn: parent
            spacing: 20
            
            Text {
                text: "收集星星: " + score + " / 3"
                font.pixelSize: 32
                color: "gold"
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: gameWin ? ["惜哉，未能窥见星辰","星辰已纳入囊中","星辰已纳入囊中","满载而归，哈哈哈"][score] : "风紧，赶紧跑"
                font.pixelSize: 48
                color: gameWin ? "#7FFF00" : "#FFA500"
                anchors.horizontalCenter: parent.horizontalCenter
            }

            Button {
                text: "结束游戏"
                anchors.horizontalCenter: parent.horizontalCenter
                onClicked: {
                    close();
                    roomScene.state = "notactive";
                    ClientInstance.replyToServer("", gameWin+","+score);
                    ClientInstance.notifyServer("PushRequest", "updatemini,confirm");
                }
                visible: root.operable
                
                background: Rectangle {
                    color: "#F44336"
                    radius: 10
                }
                
                contentItem: Text {
                    text: parent.text
                    font.pixelSize: 24
                    color: "white"
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                }
            }
        }
    }

    function loadData(data) {
        const d = data;
        operable = d[0];
    }
    
    // 初始化游戏
    Component.onCompleted: {
        // 初始设置
        bird.velocity = 0
        bird.rotation = 0
        bird.x = 150
        bird.y = root.height / 2 - bird.height / 2
    }

    // 更新数据函数（用于客户端同步）
    function updateData(data) {
        if (data.length == 0) {
            close();
            roomScene.state = "notactive";
            ClientInstance.replyToServer("", gameWin+","+score);
        }
        else{
            // 如果不是主机，处理同步数据
            if (!root.operable) {
                var parts = data.split(",");
                if (parts[0] === "sync") {
                    var syncData = JSON.parse(parts.slice(1).join(","));
                    
                    // 处理不同类型的同步事件
                    switch (syncData.type) {
                        case "game-start":{
                            // 游戏开始
                            gameRunning = true;
                            startOverlay.visible = false;
                            resultOverlay.visible = false;
                            bird.velocity = 0;
                            bird.curr = 1;
                            score = 0;
                            pipeScore = 0;
                            pipeCount = 0;
                            lastPipeX = 0;
                            
                            // 清除旧管道
                            for (var i = 0; i < pipeManager.pipes.length; i++) {
                                pipeManager.pipes[i].destroy();
                            }
                            pipeManager.pipes = [];
                            
                            // 清除旧星星
                            for (var j = 0; j < stars.length; j++) {
                                stars[j].destroy();
                            }
                            stars = [];
                            
                            // 启动游戏计时器
                            frameCount = 0;
                            gameTimer.lastTime = 0;
                            gameTimer.start();
                            break;
                        }
                        case "jump":{
                            // 跳跃事件
                            bird.velocity = jumpForce;
                            jumpEffect.start();
                            break;
                        }
                        case "pipe":{
                            // 创建新管道
                            var pipe = pipeComponent.createObject(pipeManager, {
                                objectId: syncData.id,
                                x: syncData.x,
                                y: syncData.y,
                                height: syncData.height,
                                isTop: syncData.isTop,
                                scored: false
                            });
                            pipeManager.pipes.push(pipe);
                            pipeIds[syncData.id] = pipe;
                            break;
                        }
                        case "star":{
                            // 创建新星星
                            var star = starComponent.createObject(pipeManager, {
                                objectId: syncData.id,
                                x: syncData.x,
                                y: syncData.y
                            });
                            stars.push(star);
                            starIds[syncData.id] = star;
                            break;
                        }
                        case "pipe-scored":{
                            // 管道计分
                            if (pipeIds[syncData.id]) {
                                pipeIds[syncData.id].scored = true;
                                pipeScore++;
                                
                                // 检查是否通过所有管道
                                if (pipeScore >= maxPipes) {
                                    gameWin = true;
                                    gameOver();
                                }
                            }
                            break;
                        }
                        case "star-collected":{
                            // 收集星星
                            if (starIds[syncData.id]) {
                                // 播放收集效果
                                collectEffect.createObject(root, {
                                    "x": starIds[syncData.id].x,
                                    "y": starIds[syncData.id].y
                                });
                                
                                // 移除星星
                                starIds[syncData.id].destroy();
                                delete starIds[syncData.id];
                                score++;
                            }
                            break;
                        }
                        case "game-end":{
                            // 游戏结束
                            gameRunning = false;
                            gameWin = syncData.win;
                            score = syncData.score;
                            resultOverlay.visible = true;
                            gameTimer.stop();
                            break;
                        }
                    }
                }
            }
        }
    }
}